
package security

import (
    "strings"
    "encoding/xml"
	"github.com/gomydodo/wxencrypter"
	"wxsdk/utils/misc"
)

/*		
 * Token	        公众平台上，开发者设置的Token
 * EncodingAesKey   平台参数
 * AppId            平台参数
 * timeStamp	    URL上原有参数，时间戳. t.GetString("timestamp")
 * nonce	        URL上原有参数，随机数  t.GetString("nonce")
 * msgSign          URL上原有参数          t.GetString("msg_signature")
 * msgEncrypt	    前文描述密文消息体     t.Ctx.Input.RequestBody
 */		
		
func DecrypterToStruct(Token,EncodingAesKey,AppId,timeStamp,nonce,msgSign string,msgEncrypt []byte,rsp interface{}) error {
	e, err := wxencrypter.NewEncrypter(Token, EncodingAesKey, AppId)
	if err != nil {
		return err
	}
	b, err := e.Decrypt(msgSign, timeStamp, nonce, msgEncrypt)
	if err != nil {
		return err
	}
	if rsp != nil {
		if err := xml.Unmarshal(b, &rsp); err != nil {
		    return err
	    }
	}
	return nil
}

func DecrypterXmlToMap(Token,EncodingAesKey,AppId,timeStamp,nonce,msgSign string,msgEncrypt []byte) (map[string]string, error) {
	e, err := wxencrypter.NewEncrypter(Token, EncodingAesKey, AppId)
	if err != nil {
		return map[string]string{}, err
	}
	b, err := e.Decrypt(msgSign, timeStamp, nonce, msgEncrypt)
	if err != nil {
		return map[string]string{}, err
	}
	reader := strings.NewReader(string(b))
	reqMap, err := misc.DecodeXMLToMap(reader)
	if err != nil {
		return map[string]string{}, err
	}
	return reqMap, nil
}

